import re
from flask import Flask,request,jsonify
from flask_cors.core import ensure_iterable
# 实现orm，对象关系映射
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy
from config import Config
from flask_cors import CORS
import json
import os

app = Flask(__name__)
db = SQLAlchemy(app)
CORS(app)
app.config.from_object(Config)
# 创建分类表
class Cate(db.Model):
    __tablename__='cate'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(20),unique=True)
    level = db.Column(db.Integer,default=1)
    pid = db.Column(db.Integer,default=0)

class Course(db.Model):
    __tablename__='course'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(50),unique=True)#名称唯一
    description = db.Column(db.Text,default='')#描述
    tname = db.Column(db.String(50),default='')#讲师
    pic = db.Column(db.String(255),default='')#图片
    vedios = db.Column(db.String(255),default='')#视频['','']
    status = db.Column(db.Integer,default=1)#审核状态
    reason=db.Column(db.String(255),default='')#失败原因
    cid =  db.Column(db.Integer,db.ForeignKey('cate.id'))#所属分类
# db.create_all()

@app.route('/cateM',methods = ['POST','GET','DELETE'])
def cateM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        try:
           id  = data['id']
        except:
            id = 0
        if id:
            Cate.query.filter_by(id=id).update({'name':data['name']})
            db.session.commit()
        else:    
            cate = Cate(name = data['name'])
            db.session.add(cate)
            db.session.commit()
        return jsonify({'code':200})

    elif request.method=='GET':
      
        page = int(request.args.get('page'))
        # 每页显示3条
        page_size = 3
        start = (page-1)*page_size
        cates =Cate.query.offset(start).limit(page_size)
        list =[]
        for i in cates:
            dict = {'id':i.id,'name':i.name}
            list.append(dict)
        total = Cate.query.count()
        
        return jsonify({'code':200,'list':list,'total':total})

    elif request.method=='DELETE':
        id = request.args.get('id')
        Cate.query.filter_by(id=id).delete()
        db.session.commit()
        return jsonify({"code":200})

    
@app.route('/getcateByid')
def getcateByid():
    id = request.args.get('id')
    cate = Cate.query.filter_by(id=id).first()
    dict = {'id':cate.id,'name':cate.name}
    return jsonify({'code':200,'cate':dict})

@app.route('/upload',methods=['POST','GET'])
def upload():
    if request.method=='POST':
        file = request.files['file']
        file.save(os.path.join('./static/upload/',file.filename))
        return jsonify({"code":200,'pic':file.filename})

    elif request.method=='GET':
        cates = Cate.query.all()
        list=[]
        for i in cates:
            dict = {'id':i.id,'name':i.name}
            list.append(dict)
        return jsonify({'code':200,'list':list})


@app.route('/courseM',methods=['POST','GET'])
def courseM():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        cuorse = Course(name=data['name'],description=data['description'],tname=data['tname'],vedios=json.dumps(data['vedios'],ensure_ascii=False),cid=data['cid'],pic=data['pic'])
        db.session.add(cuorse)
        db.session.commit()
        return jsonify({'code':200})

    elif request.method == "GET":
        #获取参数
        #当前点击的页面，如果没点击默认为1
        page = int(request.args.get('page'))
        #每页显示多少条
        size = int(request.args.get('size'))
        #读取数据
        start = (page-1)*size
        course = Course.query.offset(start).limit(size)
        #对结果解析
        list=[]
        if course:
            for i in course:
                list.append({'id':i.id,'name':i.name,'pic':i.pic,'tname':i.tname})
        #获取共有多少条记录
        total = Course.query.count()
        #返回
        return jsonify({"code":200,'list':list,'total':total})


@app.route('/courss')
def courss():
    id = request.args.get('id')
    course = Course.query.filter_by(id=id).first()
    cour = {'id':course.id,'name':course.name,'description':course.description,'tname':course.tname,'pic':course.pic,'vedios':course.vedios,'cid':course.cid}
    return jsonify({'code':200,'course':cour})



if __name__ == '__main__':
    app.run(debug=True)
    